package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.customview.GoodsAdapter;
import com.shwread.android.ui.widget.LoadingView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.JSONUtil;
import com.shwread.http.util.Logger;

import org.apache.http.Header;
import org.json.JSONException;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;

import logic.bean.OrderDetailInfo;
import logic.bean.UserAddressInfo;
import logic.constants.DefaultConsts;
import logic.util.MoneyUtil;
import logic.util.Utils;


/**
 * 订单详情
 *
 * @author xuzhijun
 * @date 2015年3月23日
 */
public class OrderDetailActivity
        extends
        BaseBusinessActivity
        implements
        OnClickListener {
    private Context context;

    private TextView tvTitle;
    private Button btnHome;
    private Button btnBack;

    private View topView;
    private View bottomView;

    private ListView listView;
    private LayoutInflater inflater;

    private UserAddressInfo addressInfo;
    private OrderDetailInfo orderDetailInfo;

    private GoodsAdapter adapter;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //top
    private TextView tvStateSucess;                                       //交易状态成功
    private TextView tvStateWaiting;                                      //交易状态未完成
    private TextView tvStateWaitingDeliver;                               //交易状态代发货
    private TextView tvStateClose;                                        //交易状态关闭

    private TextView tvPrice;                                             //实付款
    private TextView tvPriceText;                                         //实付款文字
    private LinearLayout llAddress;                                           //收货地址
    private TextView tvAdressName;                                        //收货地址的姓名
    private TextView tvAdressPhone;                                       //收货地址的电话
    private TextView tvAdress;                                            //收货地址
    private TextView tvDeliverWay;                                        //配送方式
    private TextView tvDeliverTime;                                       //配送时间
    private ImageView imgMore;                                             //
    private RelativeLayout deliverDetail;                                       //
    private LinearLayout invoiceTitleRay;                                     //发票抬头
    private LinearLayout invoiceNumRay;                                       //发票税号
    private LinearLayout invoiceContentRay;                                   //发票内容
    private LinearLayout remarkInvoiceRay;                                    //

    private double totalPrice;

    //bottom
    private TextView tvOrderDetailTitle;                                  //物品下面的抬头
    private TextView tvRemarkDetail;                                      //备注
    private TextView tvInviceTitle;                                       //发票抬头
    private TextView tvInviceNum;                                         //发票税号
    private TextView tvInviceContent;                                     //发票内容
    private TextView tvOrderNum;                                          //订单号
    private TextView tvAliPayNum;                                         //支付宝订单号
    private TextView tvTimeCreate;                                        //创建时间
    private TextView tvTimePay;                                           //付款时间
    private TextView tvTimeDeliver;                                       //发货时间
    private TextView tvTimeConfirm;                                       //确认时间
    private TextView tvTimeComment;                                       //评价时间   暂时不需要

    private Button btnBottom;

    private LinearLayout layFooter;                                           //评价时间
    private LinearLayout layAliPay;

    //加载动画
    private LoadingView loadingView;
    private int orderId;

    @Override
    public Handler getUIHandler() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.order_detail);
        context = this;
        orderId = getIntent().getExtras().getInt(DefaultConsts.ORDER_DETAIL_ORDER_ID);
        initView();
        initLoadingView();
        initData();
        initListener();

    }

    private void initView() {
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText(getResources().getString(R.string.order_detail_title));
        btnHome = (Button) findViewById(R.id.common_header_home);
        btnHome.setVisibility(View.VISIBLE);
        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);

        inflater = LayoutInflater.from(context);

        listView = (ListView) findViewById(R.id.order_detail_list);
        topView = inflater.inflate(R.layout.order_detail_top, null);
        bottomView = inflater.inflate(R.layout.order_detail_bottom, null);
        loadingView = (LoadingView) findViewById(R.id.order_detail_loading_view);

        //top
        tvStateSucess = (TextView) topView.findViewById(R.id.order_detail_top_success_tv);
        tvStateWaiting = (TextView) topView.findViewById(R.id.order_detail_top_waiting_tv);
        tvStateWaitingDeliver = (TextView) topView.findViewById(R.id.order_detail_top_waiting_deliver_tv);
        tvStateClose = (TextView) topView.findViewById(R.id.order_detail_top_close_tv);
        tvPrice = (TextView) topView.findViewById(R.id.order_detail_top_price_tv);
        tvPriceText = (TextView) topView.findViewById(R.id.order_detail_top_price_tv_text);
        llAddress = (LinearLayout) topView.findViewById(R.id.order_detail_top_address_lay);
        tvAdressName = (TextView) topView.findViewById(R.id.common_order_address_name_tv);
        tvAdressPhone = (TextView) topView.findViewById(R.id.common_order_address_phone_tv);
        tvAdress = (TextView) topView.findViewById(R.id.common_order_address_tv);
        tvDeliverWay = (TextView) topView.findViewById(R.id.order_detail_top_deliver_way_tv);
        tvDeliverTime = (TextView) topView.findViewById(R.id.order_detail_top_deliver_time_tv);
        imgMore = (ImageView) topView.findViewById(R.id.common_order_more_img);
        deliverDetail = (RelativeLayout) topView.findViewById(R.id.order_detail_top_deliver_detail_lay);
        //bottom
        remarkInvoiceRay = (LinearLayout) bottomView.findViewById(R.id.order_detail_bottom_remark_invoice_lay);
        invoiceTitleRay = (LinearLayout) bottomView.findViewById(R.id.order_detail_bottom_invoice_title_lay);
        invoiceNumRay = (LinearLayout) bottomView.findViewById(R.id.order_detail_bottom_invoice_num_lay);
        invoiceContentRay = (LinearLayout) bottomView.findViewById(R.id.order_detail_bottom_invoice_content_lay);
        tvOrderDetailTitle = (TextView) bottomView.findViewById(R.id.common_item_title_tv);
        tvRemarkDetail = (TextView) bottomView.findViewById(R.id.order_detail_bottom_remark_tv);
        tvInviceTitle = (TextView) bottomView.findViewById(R.id.order_detail_bottom_invoice_title);
        tvInviceNum = (TextView) bottomView.findViewById(R.id.order_detail_bottom_invoice_num);
        tvInviceContent = (TextView) bottomView.findViewById(R.id.order_detail_bottom_invoice_content);
        tvOrderNum = (TextView) bottomView.findViewById(R.id.order_detail_bottom_order_num_tv);
        tvAliPayNum = (TextView) bottomView.findViewById(R.id.order_detail_bottom_alipay_num_tv);
        tvTimeCreate = (TextView) bottomView.findViewById(R.id.order_detail_bottom_time_create_tv);
        tvTimePay = (TextView) bottomView.findViewById(R.id.order_detail_bottom_time_pay_tv);
        tvTimeDeliver = (TextView) bottomView.findViewById(R.id.order_detail_bottom_time_deliver_tv);
        tvTimeConfirm = (TextView) bottomView.findViewById(R.id.order_detail_bottom_time_confirm_tv);
        tvTimeComment = (TextView) bottomView.findViewById(R.id.order_detail_bottom_time_comment_tv);
        btnBottom = (Button) bottomView.findViewById(R.id.order_detail_bottom_footer_btn);
        layFooter = (LinearLayout) bottomView.findViewById(R.id.order_detail_bottom_footer_lay);
        layAliPay = (LinearLayout) bottomView.findViewById(R.id.order_detail_bottom_alipay_num_lay);

        listView.addHeaderView(topView);
        listView.addFooterView(bottomView);

    }

    private void initLoadingView() {
        loadingView.setLoadingAnim(R.drawable.home_progress);
        loadingView.changeLoadingStatus(0);
    }

    private void initData() {
        tvOrderDetailTitle.setText(R.string.order_detail_title);
        imgMore.setVisibility(View.GONE);
        InitOrder();

    }

    private void initListener() {
        btnBack.setOnClickListener(this);
        btnHome.setOnClickListener(this);
        deliverDetail.setOnClickListener(this);
        btnBottom.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_home:
                //				Utils.ToastShow(OrderDetailActivity.this, "点击了返回主页");
                //				startActivity(new Intent(context, MainActivity.class));
                BaseSimpleActivity.gotoMainActivity();
                break;
            case R.id.common_header_back:
                OrderDetailActivity.this.finish();
                break;
            case R.id.order_detail_top_deliver_detail_lay:
                Intent deliverDetailIntent = new Intent(OrderDetailActivity.this, GoodsOrderDeliverDetailActivity.class);
                startActivity(deliverDetailIntent);
                break;
            case R.id.order_detail_bottom_footer_btn:
                switch (Integer.valueOf(orderDetailInfo.getStatus())) {
                    case DefaultConsts.ORDER_DETAIL_STATE_UNPAY:
                        Intent intent = new Intent(context, OrderPayActivity.class);
                        intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_SERIAL, orderDetailInfo.getOrderSerial());
                        intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_PAY_MONEY, orderDetailInfo.getActualMoney());
                        intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_ORDER_TITLE, orderDetailInfo.getGoodsList().get(0).getTitle());
                        intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_ORDER_INTRO, orderDetailInfo.getGoodsList().get(0).getTitle());
                        startActivity(intent);
                        break;
                    case DefaultConsts.ORDER_DETAIL_STATE_DEKIVERING:
                        //TODO 确认收货
                        break;
                }
                break;
            default:
                break;
        }

    }

    private void InitOrder() {
        if (orderId > 0) {
            NewActionHelp.qryOrderInfo(context, orderId, new OrderDetailHandler());
        }

    }

    private class OrderDetailHandler
            extends
            ObjectHttpResponseHandler<OrderDetailInfo> {

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            Logger.d("错误返回码" + statusCode + responseString);
            if (statusCode == 200) {
                Utils.ToastShow(context, "解析错误");
            } else if (statusCode < 1000) {
                Utils.ToastShow(context, "网络错误" + statusCode);
            } else {
                try {
                    Utils.ToastShow(context, "请求出错" + statusCode + JSONUtil.getString(responseString));
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            loadingView.changeLoadingStatus(-1);
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, OrderDetailInfo object, String responseString) {
            Logger.d(responseString);
            orderDetailInfo = object;
            tvPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(orderDetailInfo.getTotalMoney(), 100)));
            adapter = new GoodsAdapter(context, orderDetailInfo.getGoodsList());

            if (orderDetailInfo.getDeliveryAddress() != null) {
                llAddress.setVisibility(View.VISIBLE);
                deliverDetail.setVisibility(View.VISIBLE);
                tvAdressName.setText(orderDetailInfo.getDeliveryAddress().getName());
                tvAdressPhone.setText(orderDetailInfo.getDeliveryAddress().getPhone());
                tvAdress.setText("收货地址：" + orderDetailInfo.getDeliveryAddress().getProvinceName() + orderDetailInfo.getDeliveryAddress().getCityName() + orderDetailInfo.getDeliveryAddress().getAreaName() + orderDetailInfo.getDeliveryAddress().getDetailAddress());
            }

            tvOrderNum.setText("" + orderDetailInfo.getOrderSerial());
            if (orderDetailInfo.getExpressMoney() == 0) {
                tvDeliverWay.setText("配送金额：免配送费");
            } else {
                tvDeliverWay.setText("配送金额：" + Utils.getMoneyFormat(MoneyUtil.divide(orderDetailInfo.getExpressMoney(), 100)) + "元");
            }
            switch (orderDetailInfo.getDelivelyTimeType()) {
                case DefaultConsts.ORDER_DETAIL_DELIVER_ALLDAY:
                    tvDeliverTime.setText("配送时间：全天");
                    break;
                case DefaultConsts.ORDER_DETAIL_DELIVER_WORKDAY:
                    tvDeliverTime.setText("配送时间：工作日");
                    break;
                case DefaultConsts.ORDER_DETAIL_DELIVER_HOLIDAY:
                    tvDeliverTime.setText("配送时间：假日");
                    break;
                default:
                    break;
            }

            if (!Utils.isEmpty(orderDetailInfo.getRemark()) || !Utils.isEmpty(orderDetailInfo.getInvoiceAccount())) {
                remarkInvoiceRay.setVisibility(View.VISIBLE);
                if (!Utils.isEmpty(orderDetailInfo.getRemark())) {
                    tvRemarkDetail.setText("备注：" + orderDetailInfo.getRemark());
                    tvRemarkDetail.setVisibility(View.VISIBLE);
                }
                if (!Utils.isEmpty(orderDetailInfo.getInvoiceAccount())) {
                    invoiceTitleRay.setVisibility(View.VISIBLE);
                    tvInviceTitle.setText(orderDetailInfo.getInvoiceAccount());
                }
                if (!Utils.isEmpty(orderDetailInfo.getInvoiceCode())) {
                    invoiceNumRay.setVisibility(View.VISIBLE);
                    tvInviceNum.setText(orderDetailInfo.getInvoiceCode());
                }
                if (!Utils.isEmpty(orderDetailInfo.getInvoiceContent())) {
                    invoiceContentRay.setVisibility(View.VISIBLE);
                    tvInviceContent.setText(orderDetailInfo.getInvoiceContent());
                }

            }

            if (!Utils.isEmpty(orderDetailInfo.getStatus())) {
                switch (Integer.valueOf(orderDetailInfo.getStatus())) {
                    case DefaultConsts.ORDER_DETAIL_STATE_UNPAY://代付款
                        unPay();
                        setBtn("付款");
                        tvStateSucess.setVisibility(View.GONE);
                        tvStateWaiting.setVisibility(View.VISIBLE);
                        tvStateWaitingDeliver.setVisibility(View.GONE);
                        tvStateClose.setVisibility(View.GONE);
                        tvStateWaiting.setText("待付款");
                        break;
                    case DefaultConsts.ORDER_DETAIL_STATE_UNDELIVER://付款成功（待发货）
                        unDeliver();
                        tvStateSucess.setVisibility(View.GONE);
                        tvStateWaiting.setVisibility(View.GONE);
                        tvStateWaitingDeliver.setVisibility(View.VISIBLE);
                        tvStateClose.setVisibility(View.GONE);
                        //						tvStateWaiting.setText("待发货");
                        break;
                    case DefaultConsts.ORDER_DETAIL_STATE_DEKIVERING://已发货（待收获）
                        /******* 已发货先按照交易完成处理 ********/
//						confirm();
                        delivering();
                        tvStateSucess.setVisibility(View.VISIBLE);
                        tvStateWaiting.setVisibility(View.GONE);
                        tvStateWaitingDeliver.setVisibility(View.GONE);
                        tvStateClose.setVisibility(View.GONE);
                        break;
                    /***************/

                    //						delivering();
                    //						setBtn("确认收货");
                    //						tvStateSucess.setVisibility(View.GONE);
                    //						tvStateWaiting.setVisibility(View.VISIBLE);
                    //						tvStateWaitingDeliver.setVisibility(View.GONE);
                    //						tvStateClose.setVisibility(View.GONE);
                    //						tvStateWaiting.setText("待收货");
                    //						break;
                    case DefaultConsts.ORDER_DETAIL_STATE_FINISHED://交易完成
//						confirm();
                        tvStateSucess.setVisibility(View.VISIBLE);
                        tvStateWaiting.setVisibility(View.GONE);
                        break;
                    case DefaultConsts.ORDER_DETAIL_STATE_CLOSE://交易取消
                        unPay();
                        tvStateSucess.setVisibility(View.GONE);
                        tvStateWaiting.setVisibility(View.GONE);
                        tvStateWaitingDeliver.setVisibility(View.GONE);
                        tvStateClose.setVisibility(View.VISIBLE);
                        //						tvStateWaiting.setText("交易关闭");
                        tvStateWaiting.setCompoundDrawables(null, null, null, null);
                        tvPrice.setVisibility(View.GONE);
                        tvPriceText.setVisibility(View.GONE);
                        break;

                }
            }
            listView.setAdapter(adapter);
            loadingView.setVisibility(View.GONE);

        }

        @Override
        public Type getType() {
            return new TypeToken<OrderDetailInfo>() {
            }.getType();
        }

    }

    private void confirm() {
        delivering();
        //		tvTimeConfirm.setText("确认时间：" + format.format(new Date(orderDetailInfo.getReceiveConfirmTime())));

        /***** 确认时间先按发货时间算 ******/
        tvTimeConfirm.setText("确认时间：" + format.format(new Date(orderDetailInfo.getDeliverTime())));
        tvTimeConfirm.setVisibility(View.VISIBLE);
    }

    private void delivering() {
        unDeliver();
        tvTimeDeliver.setText("发货时间：" + format.format(new Date(orderDetailInfo.getDeliverTime())));
        tvTimeDeliver.setVisibility(View.VISIBLE);
    }

    private void unDeliver() {
        unPay();

        tvAliPayNum.setText(orderDetailInfo.getAliPayOrderNo());
        layAliPay.setVisibility(View.VISIBLE);

        tvTimePay.setText("付款时间：" + format.format(new Date(orderDetailInfo.getPayTime())));
        tvTimePay.setVisibility(View.VISIBLE);
    }

    private void unPay() {
        tvTimeCreate.setText("创建时间：" + format.format(new Date(orderDetailInfo.getCreateTime())));
        tvTimeCreate.setVisibility(View.VISIBLE);
    }

    private void setBtn(String str) {
        btnBottom.setText(str);
        layFooter.setVisibility(View.VISIBLE);
    }
}
